/**
 * 
 */
package pt.mleiria.crypto.signatures;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Date;

/**
 * @author NB13712
 * 
 */
public class StrongClient {
	public void sendAuthentication(String user, PrivateKey key,
			OutputStream outStream) throws IOException,
			NoSuchAlgorithmException, InvalidKeyException, SignatureException {

		DataOutputStream out = new DataOutputStream(outStream);
		long t = (new Date()).getTime();
		double q = Math.random();
		Signature s = Signature.getInstance("DSA");
		s.initSign(key);
		byte[] bytes = ByteBuffer.allocate(8).putLong((long)(t + q)).array();
		s.update(bytes);
		//s.update(Protection.makeBytes(t, q));
		byte[] signature = s.sign();
		out.writeUTF(user);
		out.writeLong(t);
		out.writeDouble(q);
		out.writeInt(signature.length);
		out.write(signature);
		out.flush();
	}

	public static void main(String[] args) throws Exception {
		if (args.length != 5) {
			System.out.println("Usage: StrongClient host keystore storepass alias keypass");
			return;
		}
		String host = args[0];
		String keystorefile = args[1];
		String storepass = args[2];
		String alias = args[3];
		String keypass = args[4];
		int port = 7999;
		Socket s = new Socket(host, port);
		StrongClient client = new StrongClient();
		KeyStore keystore = KeyStore.getInstance("JKS");
		keystore.load(new FileInputStream(keystorefile), storepass.toCharArray());
		//PrivateKey key = keystore.getPrivateKey(alias, keypass);
		KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)keystore.getEntry(alias,  new KeyStore.PasswordProtection(storepass.toCharArray()));
	    PrivateKey key = pkEntry.getPrivateKey();

		client.sendAuthentication(alias, key, s.getOutputStream());
		s.close();
	}
}
